/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TrabInsertPanel.java
 *
 * Created on 29/11/2011, 23:21:21
 */

package proj5labbd.graphics.trabalho;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class TrabInsertPanel extends OperationPanel {

    /** Creates new form TrabInsertPanel */
    public TrabInsertPanel(TrabFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbInsert.addActionListener(new TrabAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jpnParam = new javax.swing.JPanel();
        jlbInicio = new javax.swing.JLabel();
        jlbFim = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbDepartamento = new javax.swing.JTable();
        jlbDepartamento = new javax.swing.JLabel();
        jlbFuncionario = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtbFuncionario = new javax.swing.JTable();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jbInsert = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(jTable2);

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da inserção"));

        jlbInicio.setText("Início");

        jlbFim.setText("Fim");

        jtbDepartamento.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbDepartamento);

        jlbDepartamento.setText("Departamento");

        jlbFuncionario.setText("Funcionário");

        jtbFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane4.setViewportView(jtbFuncionario);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(54, 54, 54)
                        .addComponent(jlbFim)
                        .addGap(352, 352, 352))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbDepartamento)
                        .addContainerGap(446, Short.MAX_VALUE))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbFuncionario)
                        .addContainerGap(468, Short.MAX_VALUE))))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbInicio)
                    .addComponent(jlbFim))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbDepartamento)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbFuncionario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addComponent(jbInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Método para pegar os dados das tabelas a serem exibidas e colocá-los nas JTables
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Método para controlar os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbDepartamento.clearSelection();
        jtbFuncionario.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JButton jbInsert;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDepartamento;
    private javax.swing.JLabel jlbFim;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbInicio;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbDepartamento;
    private javax.swing.JTable jtbFuncionario;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata as tabelas departamento e funcionario para serem exibidas
     */
    public void setupTable() throws SQLException {
        String [] titlesDe = {"ID","Departamento"};
        String [] fieldsDe = {"idDe","nomeDe"};
        String [][] dept = dbInterface.view(fieldsDe,null,new String[]{"departamento"});
        String [] fieldsFu = {"funcionario.idFu","funcionario.nomeCompletoFu","tipoFuncionario.descricaoTipoFu"};
        String [] params = {"funcionario.idTipoFu=tipoFuncionario.idTipoFu"};
        String [] titlesFu = {"ID","Nome","Carreira"};
        String [][] func = dbInterface.view(fieldsFu, params, new String[]{"funcionario","tipoFuncionario"});
        DefaultTableModel model = new DefaultTableModel(dept,titlesDe);
        jtbDepartamento.setModel(model);
        model = new DefaultTableModel(func,titlesFu);
        jtbFuncionario.setModel(model);
    }

    class TrabAction implements ActionListener {
        
        /*
         * Controla os eventos de inserção
         */
        public void actionPerformed(ActionEvent e) {

                if ( jtbDepartamento.getSelectedRowCount() == 1 && jtbFuncionario.getSelectedRowCount() == 1 &&
                        jftxtIni.getText().compareTo("  -  -    ") != 0 ) {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add("TO_DATE('"+jftxtIni.getText()+"','DD-MM-YYYY')");
                    fields.add("dataInicioTr");

                    if (jftxtFim.getText().compareTo("  -  -    ") != 0) {
                        params.add("TO_DATE('"+jftxtFim.getText()+"','DD-MM-YYYY')");
                        fields.add("dataFimTr");
                    }

                    params.add((String)jtbFuncionario.getValueAt(jtbFuncionario.getSelectedRow(), 0));
                    fields.add("idFu");

                    params.add((String)jtbDepartamento.getValueAt(jtbDepartamento.getSelectedRow(), 0));
                    fields.add("idDe");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"trabalho"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtbFuncionario.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um funcionário.");
                }
                else if (jtbDepartamento.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um departamento.");
                }

            }
    }
    

}
